use MapLoader;
use Tiles;
use MapCell;

package PlainFileMapLoader;
@ISA = qw/MapLoader/;


sub init{
    my $self = shift;

    $self->{CODE} = {
	'#' => "Wall",
	'^' => "Wall",
	'I' => "Ground",
	'.' => "Ground"
    };
}

sub invalidParams{
    my $self = shift;
    my @invalid = ();

    my $filename = $self->{PARAMS}->{FILENAME};

    push(@invalid, "FILENAME") unless (defined($filename));
    
    return @invalid;
}

sub __do_generation{
    my $self = shift;

    my $filename = $self->{PARAMS}->{FILENAME};
    open(MAPFILE, $filename);

    my @columns = ();

    my ($x, $y) = (0,0);
    my $cell = undef;

    while(<MAPFILE>){
	chomp();
	my @chars = split //;

	foreach my $char (@chars){
	    $cell = MapCell->spawn;

	    my $class = $self->{CODE}->{$char};

	    if($class eq "Wall"){
		my $constr = Wall->spawn;
		$constr->pic($char);
		$cell->contents->add($constr, "CONSTRUCTION");
	    }
	    $class = "Ground";
	    my $tile = eval($class."->spawn()");

	    $tile->pic($char) if($class ne "Wall");


	    my $column = $columns[$x];
	    if(!defined $column){
		$column = [];
		$columns[$x] = $column;
	    }

	    $cell->contents->add($tile, "FLOOR");
	    $columns->[$x][$y] = $cell;
	    $x++;
	} # char
	$y++;
	$x = 0;
    } # line

    my $map = Map->new($columns);
    return $map;
}

1;
